//
//  ETH+Account+BIP32.swift
//  XHWalletUtils
//
//  Created by xinph on 2020/5/17.
//  Copyright © 2020 xinph. All rights reserved.
//

import Foundation

extension ETH: BIP32 {
    public func UNSAFE_getPrivateAndPublicKey(password: String, address: String) -> coswift.Promise<(pub: String, pri: String)> {
        let promise = coswift.Promise<(pub: String, pri: String)>()
        
        guard address.isEmpty == false else {
            print(addressNotFound)
            promise.reject(error: XHError(generatePrivateKeyFailure))
            return promise
        }
        guard let keystore = self.ethKeystore else {
            print(notSuppurt)
            promise.reject(error: XHError(generatePrivateKeyFailure))
            return promise
        }
        var `private`: String = ""
        var `public` = ""
        do {
            let data = try keystore.UNSAFE_getPrivateKeyData(password: password, account: EthereumAddress(address)!)
            `public` = Web3.Utils.privateToPublic(data, compressed: true)?.toHexString() ?? ""
            `private` = data.toHexString()
        } catch (let err) {
            print(err)
        }
        promise.fulfill(value: (pub: `public`.hf_addHexPrefix(), pri: `private`.hf_addHexPrefix()))
        return promise
    }
    
}

